import { fileURLToPath, URL } from 'node:url'

import { loadEnv, type ConfigEnv, type UserConfig } from 'vite'
import { createVitePlugins } from './build/vite'
import viewport from 'postcss-mobile-forever'
import autoprefixer from 'autoprefixer'
import { buildPlugins, externalGlobalsObj } from './build/vite/build'
// https://vitejs.dev/config/
export default ({ mode }: ConfigEnv): UserConfig => {
  const root = process.cwd()
  const env = loadEnv(mode, root)
  return {
    base: env.VITE_APP_PUBLIC_PATH,
    plugins: createVitePlugins(),
    server: {
      host: true,
      port: 3000,
      proxy: {
        '/api': {
          target: '',
          ws: false,
          changeOrigin: true
        }
      }
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '~': fileURLToPath(new URL('./src/assets', import.meta.url))
      }
    },

    css: {
      postcss: {
        plugins: [
          autoprefixer(),
          // https://github.com/wswmsword/postcss-mobile-forever
          viewport({
            appSelector: '#app',
            viewportWidth: 375,
            maxDisplayWidth: 600,
            rootContainingBlockSelectorList: ['van-tabbar', 'van-popup']
          })
        ]
      }
    },

    build: {
      // cssCodeSplit: false,
      // chunkSizeWarningLimit: 2048,
      rollupOptions: {
        external: Object.keys(externalGlobalsObj),
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          // 最小化拆分包
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          }
        },
        plugins: buildPlugins
      }
    }
  }
}
